import { computed } from 'vue';
import type { RouteRecordRaw, RouteRecordNormalized } from 'vue-router';
import { appRoutes } from '@/router/routes';
import usePermission from '@/hooks/usePermission';
import { useUserStore } from '@/store';
import { formatDynamicRoutes } from '@/utils/dynamic-routes';
import { cloneDeep } from 'lodash';
import { router } from '@/router';

// 检查是否是外部链接
function isExternalLink(path: string) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

export default function useMenuTree() {
  const permission = usePermission();
  const userStore = useUserStore();

  // 检查路由是否存在
  const isRouteExists = (name: string) => {
    const exists = router.hasRoute(name);
    return exists;
  };

  // 获取菜单数据，优先使用后端返回的菜单数据，如果不存在则使用本地路由配置
  const appRoute = computed(() => {
    // 如果存在后端返回的菜单数据，则优先使用
    if (userStore.menus && userStore.menus.length > 0) {
      try {
        const routes = formatDynamicRoutes(userStore.menus).map(el => {
          const { name, path, meta, redirect, children } = el;
          // 检查每个菜单项是否有效
          return {
            name,
            path,
            meta,
            redirect,
            children
          };
        });
        return routes;
      } catch (error) {
        return [];
      }
    }

    // 否则使用本地路由配置
    const routes = appRoutes.map(el => {
      const { name, path, meta, redirect, children } = el;
      return {
        name,
        path,
        meta,
        redirect,
        children
      };
    });
    return routes;
  });

  const menuTree = computed(() => {
    const copyRouter = cloneDeep(appRoute.value) as RouteRecordNormalized[];

    function travel(_routes: RouteRecordRaw[], layer: number) {
      if (!_routes) return null;

      const collector: any = _routes.map(element => {
        // 检查路由是否有效
        if (element.meta?.hideInMenu) {
          return null;
        }

        // 检查权限
        if (!permission.accessRouter(element)) {
          return null;
        }

        // 检查是否是外部链接
        const isExternal = element.path && isExternalLink(element.path);
        const routeName = element.name ? String(element.name) : '';

        // 处理菜单项
        const menuItem: any = {
          title: element.meta?.title || element.meta?.locale || '',
          name: routeName,
          path: element.path || '',
          meta: {
            ...element.meta,
            locale: element.meta?.title || element.meta?.locale || '', // 确保locale字段存在
            title: element.meta?.title || element.meta?.locale || '' // 确保title字段存在
          },
          icon: element.meta?.icon || '',
          order: element.meta?.orderNo || element.meta?.order || 0,
          hideInMenu: element.meta?.hideInMenu || false
        };

        // 如果是外部链接，添加特殊标记
        if (isExternal) {
          menuItem.external = true;
        }

        // 处理子菜单
        const visibleChildren = element.children?.filter(
          child => !child.meta?.hideInMenu && permission.accessRouter(child)
        );

        if (visibleChildren?.length) {
          menuItem.children = travel(visibleChildren, layer + 1);
        } else {
          // console.log(`菜单项 [${element.name}] 没有可见子项`);
        }

        return menuItem;
      });

      // 过滤掉无效菜单项
      const validMenuItems = collector.filter(Boolean);

      // 按照 order 排序
      return validMenuItems.sort((a: any, b: any) => {
        return (a.order || 0) - (b.order || 0);
      });
    }

    const result = travel(copyRouter, 0);
    return result;
  });

  return {
    menuTree
  };
}
